package com.example.bysj.config;
//201902104061徐中堂
import com.example.bysj.Service.UserService;
import com.example.bysj.domain.User;
import com.example.bysj.domain.authority.Role;

import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;


import javax.annotation.Resource;
import java.util.Collection;

public class UserRealm extends AuthorizingRealm {
    @Resource
    private UserService userService;

    @Override
    //身份验证
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //验证用户名和密码
        String userName = (String) token.getPrincipal();
        String password = new String((char[]) token.getCredentials());//证明
        //根据用户名获取用户
        User user = userService.getByUserName(userName);
        if (user == null){
            throw new UnknownAccountException("找不到该用户！");
        } else if(!password.equals(user.getPassword())){
            throw new IncorrectCredentialsException("密码不匹配");
        }
        //建立一个认证模块，包括身份证明信息
        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
                user,//传入user
                user.getPassword(),
                getName()
        );
        return authenticationInfo;
    }
    //授权，角色和权限验证
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        //授权 新建一个授权模块 SimpleAuthorizationInfo 把 权限赋值给当前的用户
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        //如果身份认证的时候没有传入User对象，这里只能取到userName
        //也就是SimpleAuthenticationInfo构造的时候第一个参数传递需要User对象
        User user  = (User)principals.getPrimaryPrincipal();
        Collection<Role> roles = user.getRoles();
        for (Role role:roles){
            //添加角色
            authorizationInfo.addRole(role.getRole());
            for (com.example.bysj.domain.authority.Resource resource:role.getResources()){
                //添加权限
                authorizationInfo.addStringPermission(resource.getPermission());
            }
        }
        return authorizationInfo;
    }
}
